import os
import time
import streamlit as st

from ebooklib import epub
from .crawler import WebCrawler
from .config_manager import ConfigManager
from .download_queue import DownloadQueue
from .library_manager import LibraryManager
from .metadata_fetcher import MetadataFetcher

SAVE_PATH = os.path.join(os.getcwd(), 'downloads')
PIC_PATH = os.path.join(SAVE_PATH, 'pics')
NOVEL_PATH = os.path.join(SAVE_PATH, 'novels')

crawler = WebCrawler()
config = ConfigManager()
library_manager = LibraryManager()
metadata_fetcher = MetadataFetcher()


class Downloader:
    def __init__(self):
        if not os.path.exists(SAVE_PATH):
            os.makedirs(SAVE_PATH)
        if not os.path.exists(PIC_PATH):
            os.makedirs(PIC_PATH)
        if not os.path.exists(NOVEL_PATH):
            os.makedirs(NOVEL_PATH)
        
        # Initialize download queue with callback
        self.queue = DownloadQueue(self._download_task_callback)

    def download_pictures(self, urls, volume_name, novel_name, progress_container, cnt=''):
        """下载指定卷的所有图片"""
        volume_path = os.path.join(PIC_PATH, novel_name, volume_name)
        if cnt != '':
            volume_path = os.path.join(PIC_PATH, novel_name, f"{cnt}_{volume_name}")
        if not os.path.exists(volume_path):
            os.makedirs(volume_path)

        with progress_container:
            bar = st.progress(0)
            for i, url in enumerate(urls):
                bar.progress(i / len(urls), f"⏬ 正在下载 {volume_name} 第{i + 1}/{len(urls)}张图片...")
                suffix = url.split('.')[-1]

                content = crawler.get_image_content(url)
                if content:
                    file_path = f"{volume_path}/{i + 1}.{suffix}"
                    with open(file_path, 'wb') as f:
                        f.write(content)
                    # Use configurable delay between image downloads
                    image_delay = config.get('download', 'image_download_delay') or 1.0
                    if i < len(urls) - 1:  # Don't delay after the last image
                        time.sleep(image_delay)

            bar.progress(1.0, "✅ 下载完成")
    
    def download_volume(self, volume_name, book):
        ebook = epub.EpubBook()
        ebook.set_language('zh')
        ebook.add_author(book.basic_info['作者'])
        for tag in book.basic_info['标签']:
            ebook.add_metadata('DC', 'subject', tag)
        ebook.add_metadata('DC', 'description', book.basic_info['简介'])
        ebook.add_metadata('DC', 'publisher', book.basic_info['出版社'])

        chapters = []

        volume = book.volumes[volume_name]
        # book_name = book.get_formatted_title(config.get('download', 'full_title'))
        book_name = book.basic_info["标题"]
        ebook.set_title(f"{book_name} {volume_name}")
        bar = st.progress(0)

        chapter_index = 0

        for item in volume:
            chapter_index += 1
            name = item['name']
            chapter_name = str(chapter_index) + "-" + name
            link = f'{book.base_chapter_url}{item["link"]}'
            chapter = epub.EpubHtml(title=name, file_name=f'{chapter_name}.xhtml', lang='zh')

            chapter.add_link(href='style/style.css', rel='stylesheet', type='text/css')

            if name == '插图':
                ch_urls = book.get_chapter_image_urls(volume_name)
                pic_bar = st.progress(0)
                chapter.content = ''
                for url in ch_urls:
                    pic_bar.progress(ch_urls.index(url) / len(ch_urls),
                                    f"⏬ 正在下载 {volume_name} 第{ch_urls.index(url) + 1}/{len(ch_urls)}张图片...")
                    suffix = url.split('.')[-1]
                    content = crawler.get_image_content(url)
                    if content:
                        img_name = f'images/{volume_name}_{ch_urls.index(url) + 1}.{suffix}'
                        ebook.add_item(
                            epub.EpubItem(
                                file_name=img_name, 
                                media_type='image/jpeg', 
                                content=content
                            )
                        )
                        chapter.content += f'<img src="{img_name}">'

                        # 封面的图片位置
                        if ch_urls.index(url) == config.get('download', 'default_cover_index'):
                            # 设置分卷封面
                             ebook.set_cover(f'{volume_name}/cover.{suffix}', content)

                        # Use configurable delay between image downloads
                        image_delay = config.get('download', 'image_download_delay') or 1.0
                        if ch_urls.index(url) < len(ch_urls) - 1:  # Don't delay after the last image
                            time.sleep(image_delay)
                pic_bar.progress(1.0, f"✅ {volume_name} 图片下载完成")
            else:
                content = crawler.fetch(link).find('div', id='content')
                time.sleep(config.get('download', 'wait_time'))
                for ul_tag in content.find_all('ul'):
                    ul_tag.decompose()
                chapter.content = f'<html><h2>{name}</h2><body>{content}</body></html>'
                bar.progress(volume.index(item) / len(volume),
                                 f"⏬ 正在下载 {volume_name} 第{volume.index(item) + 1}/{len(volume)}章节...")

            ebook.add_item(chapter)
            chapters.append(chapter)
            ebook.toc.append(epub.Link(f'{chapter_name}.xhtml', name, chapter_name))

        # 添加统计/制作信息页面
        chapter = epub.EpubHtml(
            title="制作信息",
            file_name="制作信息.xhtml",
            lang="zh"
        )
        chapter.content = f"""
        <html>
            <h2>制作信息</h2>
            <body>
                <b>标题：</b>{book.basic_info["标题"]}<br/>
                <b>作者：</b>{book.basic_info["作者"]}<br/>
                <b>文库分类：</b>{book.basic_info["出版社"]}<br/>
                <b>标签：</b>{" ".join(book.basic_info["标签"])}<br/>
                <b>全文长度：</b>{book.basic_info["全文长度"]}<br/>
                <b>轻小说文库链接：</b><a href="https://www.wenku8.net/book/{book.book_id}.htm">{book.basic_info["标题"]} (ID: {book.book_id})</a><br/>
                <b>生成工具（原作者）：</b><a href="https://github.com/mj3622/Wenku8Downloader">Wenku8Downloader</a><br/>
                <b>生成工具（TTThuan自改）</b><a href="https://gitee.com/tomthethuan/wenku8-downloader-ttt-modified">wenku8-downloader-ttt-modified</a><br/>
            </body>
        </html>      
        """
        # print(chapter.content)
        chapter.add_link(href='style/style.css', rel='stylesheet', type='text/css')
        ebook.add_item(chapter)
        chapters.append(chapter)
        ebook.toc.append(epub.Link("制作信息.xhtml", "制作信息", "制作信息"))

        # Add style
        css = epub.EpubItem(
            uid="style",
            file_name="style/style.css",
            media_type="text/css",
            content=config.get_style()
        )
        ebook.add_item(css)

        # 内嵌字体，因为文件大小的原因暂时移除
        # with open("config/LXGWNeoXiHeiPlus.ttf", mode="rb") as f:
        #     font = epub.EpubItem(
        #         uid="LXGWNeoXiHeiPlus",
        #         file_name="fonts/LXGWNeoXiHeiPlus.ttf",
        #         media_type="font/ttf",
        #         content=f.read()
        #     )
        #     ebook.add_item(font)

        # with open("config/OPPO Sans 4.0.ttf", mode="rb") as f:
        #     font = epub.EpubItem(
        #         uid="OPPO Sans 4.0",
        #         file_name="fonts/OPPO Sans 4.0.ttf",
        #         media_type="font/ttf",
        #         content=f.read()
        #     )
        #     ebook.add_item(font)

        ebook.spine = ['nav'] + chapters
        ebook.add_item(epub.EpubNav())
        print(f'{book_name} {volume_name}.epub 下载完成')
        path = os.path.join(NOVEL_PATH, book_name, f'{volume_name}.epub')
        if not os.path.exists(os.path.join(NOVEL_PATH, book_name)):
            os.makedirs(os.path.join(NOVEL_PATH, book_name))
        epub.write_epub(path, ebook, {})

        bar.progress(1.0, f"✅ {book_name} {volume_name} 下载完成")
        st.success(f"小说 {book_name} {volume_name} 下载完成")

        # 返回小说的本地下载路径
        return (path, book_name, volume_name)


    def download_novel(self, book, progress_container, volume_name=None):
        ebook = epub.EpubBook()
        ebook.set_language('zh')
        ebook.add_author(book.basic_info['作者'])
        for tag in book.basic_info['标签']:
            ebook.add_metadata('DC', 'subject', tag)
        ebook.add_metadata('DC', 'description', book.basic_info['简介'])
        ebook.add_metadata('DC', 'publisher', book.basic_info['出版社'])

        chapters = []
        with progress_container:

            if volume_name=="分别下载分卷":
                bar = st.progress(0)
                all_volumes = book.volumes.keys()
                
                i = 0

                for volume_name in all_volumes:
                    bar.progress(i / len(all_volumes), 
                        f"⏬ 正在下载 {book.basic_info["标题"]} 第{i}/{len(all_volumes)}卷..."
                    )
                    self.download_volume(volume_name, book)
                    i += 1
                bar.progress(1.0, f"✅ {book.basic_info["标题"]} 下载完成")

            elif volume_name:
                # 提出指定卷的章节
                path, book_name, volume_name = self.download_volume(volume_name, book)
                with open(path, "rb") as file:
                    st.download_button(
                        label=f"通过浏览器下载 {book_name} {volume_name}.epub",
                        data=file,
                        file_name=f"{book_name} {volume_name}.epub",
                        mime="application/epub+zip"
                    )

            else:
                with st.spinner(f"正在下载封面..."):
                    # 下载整本小说
                    ebook.set_title(book.get_formatted_title(config.get('download', 'full_title')))

                    # 获取小说封面
                    cover_name = book.basic_info['cover'].split('/')[-1]
                    cover_content = book.get_cover_content()
                    ebook.set_cover(cover_name, cover_content)

                # 循环下载每一卷
                for volume_name, volume in book.volumes.items():
                    chapter = epub.EpubHtml(title=volume_name, file_name=f'{volume_name}.xhtml', lang='zh')
                    text = f'<img src=images/{volume_name}_1.jpg>'
                    bar = st.progress(0)
                    img_bar = st.progress(0)
                    for item in volume:
                        bar.progress(volume.index(item) / len(volume),
                                     f"⏬ 正在下载 {volume_name} 第{volume.index(item) + 1}/{len(volume)}章节...")
                        name = item['name']
                        link = f'{book.base_chapter_url}{item["link"]}'
                        if name == '插图':
                            ch_urls = book.get_chapter_image_urls(volume_name)
                            for url in ch_urls:
                                img_bar.progress(ch_urls.index(url) / len(ch_urls),
                                                 f"⏬ 正在下载 {volume_name} 第{ch_urls.index(url) + 1}/{len(ch_urls)}张图片...")
                                suffix = url.split('.')[-1]
                                content = crawler.get_image_content(url)
                                if content:
                                    img_name = f'images/{volume_name}_{ch_urls.index(url) + 1}.{suffix}'
                                    ebook.add_item(
                                        epub.EpubItem(file_name=img_name, media_type='image/jpeg', content=content))
                                    text += f'<img src="{img_name}">'
                                    # Use configurable delay between image downloads
                                    image_delay = config.get('download', 'image_download_delay') or 1.0
                                    if ch_urls.index(url) < len(ch_urls) - 1:  # Don't delay after the last image
                                        time.sleep(image_delay)
                            text += '<br>'
                            img_bar.progress(1.0, f'✅ {volume_name} 图片下载完成')
                        else:
                            # 处理文本
                            content = crawler.fetch(link).find('div', id='content')
                            for ul_tag in content.find_all('ul'):
                                ul_tag.decompose()
                            text += f'<h2>{name}</h2><body>{content}</body><br>'
                    chapter.content = f'<html>{text}</html>'
                    ebook.add_item(chapter)
                    chapters.append(chapter)
                    ebook.toc.append(epub.Link(f'{volume_name}.xhtml', volume_name, volume_name))
                    bar.progress(1.0, f'✅ {volume_name} 下载完成')

                ebook.spine = ['nav'] + chapters
                ebook.add_item(epub.EpubNav())
                path = os.path.join(NOVEL_PATH, f'{book.basic_info["标题"]}.epub')
                epub.write_epub(path, ebook, {})

    def add_to_queue(self, book_id: str, book_title: str, download_type: str, volume_name: str = None) -> str:
        """Add a download task to the queue"""
        return self.queue.add_task(book_id, book_title, download_type, volume_name)
    
    def get_queue_status(self) -> dict:
        """Get current queue status"""
        return self.queue.get_queue_status()
    
    def remove_from_queue(self, task_id: str) -> bool:
        """Remove a pending task from queue"""
        return self.queue.remove_task(task_id)
    
    def pause_queue(self):
        """Pause queue processing"""
        self.queue.pause_queue()
    
    def resume_queue(self):
        """Resume queue processing"""
        self.queue.resume_queue()
    
    def clear_completed(self):
        """Clear completed and failed tasks from results"""
        self.queue.clear_completed()
    
    def retry_failed_task(self, task_id: str) -> bool:
        """Retry a failed task"""
        return self.queue.retry_failed_task(task_id)
    
    def _download_task_callback(self, task, progress_callback):
        """Callback function for processing download tasks from the queue"""
        from .book import Book
        
        # Create book object
        book = Book(task.book_id)
        
        # Create a simplified progress container that doesn't use Streamlit in background threads
        class QueueProgressContainer:
            def __init__(self, callback):
                self.callback = callback
                self.current_progress = 0.0
            
            def __enter__(self):
                return self
            
            def __exit__(self, *args):
                pass
            
            def progress(self, value, text=""):
                # Simply call the callback without Streamlit functions
                self.current_progress = value
                self.callback(value, text)
        
        progress_container = QueueProgressContainer(progress_callback)
        
        # Process based on download type
        if task.download_type == "full":
            # Download complete novel - use a simplified version that doesn't require Streamlit context
            return self._download_novel_for_queue(book, progress_callback)
            
        elif task.download_type == "separate_volumes":
            # Download all volumes separately
            file_paths = []
            volumes = list(book.volumes.keys())
            for i, volume_name in enumerate(volumes):
                progress_callback(i / len(volumes), f"Processing {volume_name}")
                path = self._download_volume_for_queue(volume_name, book, lambda p, t: progress_callback((i + p) / len(volumes), f"{volume_name}: {t}"))
                file_paths.append(path)
            return file_paths
            
        elif task.download_type == "volume" and task.volume_name:
            # Download single volume
            path = self._download_volume_for_queue(task.volume_name, book, progress_callback)
            return [path]
        
        else:
            raise ValueError(f"Unknown download type: {task.download_type}")
    
    def _download_novel_for_queue(self, book, progress_callback):
        """Simplified version of download_novel for queue processing without Streamlit context"""
        from ebooklib import epub
        
        # Create EPUB book with proper metadata
        ebook = epub.EpubBook()
        ebook.set_identifier(f'wenku8-{book.book_id}')
        ebook.set_title(book.basic_info['标题'])
        ebook.set_language('zh')
        ebook.add_author(book.basic_info['作者'])
        
        # Add metadata
        for tag in book.basic_info.get('标签', []):
            ebook.add_metadata('DC', 'subject', tag)
        
        if book.basic_info.get('简介'):
            ebook.add_metadata('DC', 'description', book.basic_info['简介'])
        
        # Download and set cover
        cover_content = book.get_cover_content()
        if cover_content:
            cover_name = 'cover.jpg'
            ebook.set_cover(cover_name, cover_content)
        
        chapters = []
        spine_items = []
        
        # Add CSS
        css_content = config.get_style()
        css_item = epub.EpubItem(
            uid="style",
            file_name="style/style.css",
            media_type="text/css",
            content=css_content
        )
        ebook.add_item(css_item)
        
        # Process each volume
        total_volumes = len(book.volumes)
        for volume_idx, (volume_name, volume) in enumerate(book.volumes.items()):
            progress_callback(volume_idx / total_volumes, f"Processing {volume_name}")
            
            # Create volume chapter
            volume_chapter = epub.EpubHtml(
                title=volume_name,
                file_name=f'{volume_name}.xhtml',
                lang='zh'
            )
            volume_chapter.add_link(href='style/style.css', rel='stylesheet', type='text/css')
            
            content_html = f'<html><head><title>{volume_name}</title></head><body>'
            content_html += f'<h1>{volume_name}</h1>'
            
            # Process each chapter in the volume
            total_chapters = len(volume)
            for chapter_idx, item in enumerate(volume):
                progress_callback((volume_idx + chapter_idx / total_chapters) / total_volumes, 
                                f"{volume_name}: {item['name']}")
                
                name = item['name']
                link = f'{book.base_chapter_url}{item["link"]}'
                
                if name == '插图':
                    # Handle images
                    ch_urls = book.get_chapter_image_urls(volume_name)
                    content_html += f'<h2>插图</h2><div>'
                    for img_idx, url in enumerate(ch_urls):
                        img_content = crawler.get_image_content(url)
                        if img_content:
                            suffix = url.split('.')[-1]
                            img_name = f'images/{volume_name}_{img_idx + 1}.{suffix}'
                            ebook.add_item(
                                epub.EpubItem(file_name=img_name, media_type='image/jpeg', content=img_content)
                            )
                            content_html += f'<img src="{img_name}" alt="插图 {img_idx + 1}"/>'
                            time.sleep(config.get('download', 'image_download_delay') or 1.0)
                    content_html += '</div>'
                else:
                    # Handle text content
                    chapter_content = crawler.fetch(link).find('div', id='content')
                    if chapter_content:
                        # Clean up HTML
                        for ul_tag in chapter_content.find_all('ul'):
                            ul_tag.decompose()
                        
                        content_html += f'<h2>{name}</h2>'
                        content_html += f'<div>{str(chapter_content)}</div>'
                
                time.sleep(config.get('download', 'wait_time'))
            
            content_html += '</body></html>'
            volume_chapter.content = content_html
            ebook.add_item(volume_chapter)
            chapters.append(volume_chapter)
            spine_items.append(volume_chapter)
        
        # Add navigation
        ebook.add_item(epub.EpubNav())
        
        # Set spine
        ebook.spine = ['nav'] + spine_items
        
        # Create table of contents
        toc = []
        for volume_name in book.volumes.keys():
            toc.append(epub.Link(f'{volume_name}.xhtml', volume_name, volume_name))
        ebook.toc = toc
        
        # Ensure downloads directory exists
        if not os.path.exists(NOVEL_PATH):
            os.makedirs(NOVEL_PATH)
        
        path = os.path.join(NOVEL_PATH, f'{book.basic_info["标题"]}.epub')
        epub.write_epub(path, ebook, {})
        
        progress_callback(1.0, "Download complete")
        return [path]
    
    def _download_volume_for_queue(self, volume_name, book, progress_callback):
        """Simplified version of download_volume for queue processing without Streamlit context"""
        from ebooklib import epub
        
        # Create EPUB book with proper metadata
        ebook = epub.EpubBook()
        ebook.set_identifier(f'wenku8-{book.book_id}-{volume_name}')
        
        book_name = book.basic_info["标题"]
        ebook.set_title(f"{book_name} {volume_name}")
        ebook.set_language('zh')
        ebook.add_author(book.basic_info['作者'])
        
        # Add metadata
        for tag in book.basic_info.get('标签', []):
            ebook.add_metadata('DC', 'subject', tag)
        
        if book.basic_info.get('简介'):
            ebook.add_metadata('DC', 'description', book.basic_info['简介'])
        
        # Add CSS
        css_content = config.get_style()
        css_item = epub.EpubItem(
            uid="style",
            file_name="style/style.css",
            media_type="text/css",
            content=css_content
        )
        ebook.add_item(css_item)
        
        volume = book.volumes[volume_name]
        chapters = []
        spine_items = []
        
        # Process each item in the volume
        total_items = len(volume)
        for item_idx, item in enumerate(volume):
            progress_callback(item_idx / total_items, f"Processing {item['name']}")
            
            name = item['name']
            link = f'{book.base_chapter_url}{item["link"]}'
            
            if name == '插图':
                # Handle images
                ch_urls = book.get_chapter_image_urls(volume_name)
                
                # Create a chapter for images
                image_chapter = epub.EpubHtml(
                    title="插图",
                    file_name=f'{volume_name}_images.xhtml',
                    lang='zh'
                )
                image_chapter.add_link(href='style/style.css', rel='stylesheet', type='text/css')
                
                content_html = '<html><head><title>插图</title></head><body><h1>插图</h1><div>'
                
                for img_idx, url in enumerate(ch_urls):
                    img_content = crawler.get_image_content(url)
                    if img_content:
                        suffix = url.split('.')[-1]
                        img_name = f'images/{volume_name}_{img_idx + 1}.{suffix}'
                        ebook.add_item(
                            epub.EpubItem(file_name=img_name, media_type='image/jpeg', content=img_content)
                        )
                        content_html += f'<img src="{img_name}" alt="插图 {img_idx + 1}"/>'
                        time.sleep(config.get('download', 'image_download_delay') or 1.0)
                
                content_html += '</div></body></html>'
                image_chapter.content = content_html
                ebook.add_item(image_chapter)
                chapters.append(image_chapter)
                spine_items.append(image_chapter)
                
            else:
                # Handle text content
                chapter_content = crawler.fetch(link).find('div', id='content')
                if chapter_content:
                    # Clean up HTML
                    for ul_tag in chapter_content.find_all('ul'):
                        ul_tag.decompose()
                    
                    chapter = epub.EpubHtml(
                        title=name,
                        file_name=f'{volume_name}_{name}.xhtml',
                        lang='zh'
                    )
                    chapter.add_link(href='style/style.css', rel='stylesheet', type='text/css')
                    
                    chapter.content = f'<html><head><title>{name}</title></head><body><h1>{name}</h1><div>{str(chapter_content)}</div></body></html>'
                    ebook.add_item(chapter)
                    chapters.append(chapter)
                    spine_items.append(chapter)
            
            time.sleep(config.get('download', 'wait_time'))
        
        # Add navigation and finalize
        ebook.add_item(epub.EpubNav())
        ebook.spine = ['nav'] + spine_items
        
        # Create directory if needed
        volume_dir = os.path.join(NOVEL_PATH, book_name)
        if not os.path.exists(volume_dir):
            os.makedirs(volume_dir)
        
        path = os.path.join(volume_dir, f'{volume_name}.epub')
        epub.write_epub(path, ebook, {})
        
        progress_callback(1.0, "Volume download complete")
        return path

    def _add_book_to_library(self, book, file_path, download_type="full"):
        """
        将下载的书籍添加到图书馆数据库
        
        Args:
            book: Book对象
            file_path: 下载的文件路径
            download_type: 下载类型
        """
        try:
            # 获取文件大小
            file_size = os.path.getsize(file_path) if os.path.exists(file_path) else 0
            
            # 准备书籍数据
            book_data = {
                'book_id': book.book_id,
                'title': book.basic_info['标题'],
                'author': book.basic_info.get('作者', '未知作者'),
                'publisher': book.basic_info.get('出版社', ''),
                'description': book.basic_info.get('简介', ''),
                'tags': book.basic_info.get('标签', []),
                'cover_url': book.basic_info.get('cover', ''),
                'download_path': file_path,
                'file_size': file_size,
                'file_format': 'epub',
                'wenku8_url': f"https://www.wenku8.net/book/{book.book_id}.htm",
                'metadata_hash': self._generate_metadata_hash(book)
            }
            
            # 添加到图书馆数据库
            success = library_manager.add_book(book_data)
            if success:
                print(f"书籍已添加到图书馆: {book.basic_info['标题']}")
            else:
                print(f"添加到图书馆失败: {book.basic_info['标题']}")
                
        except Exception as e:
            print(f"添加到图书馆时出错: {e}")

    def _generate_metadata_hash(self, book):
        """生成元数据哈希用于检测变更"""
        import hashlib
        text = f"{book.book_id}_{book.basic_info['标题']}_{book.basic_info.get('作者', '')}".encode('utf-8')
        return hashlib.md5(text).hexdigest()

    def _download_task_callback(self, task_data, result):
        """
        下载任务完成后的回调函数，用于将书籍添加到图书馆
        """
        try:
            if result and result.get('success', False):
                # 获取Book对象
                from .book import Book
                book = Book(task_data['book_id'])
                
                # 根据下载类型确定文件路径
                file_path = None
                if task_data['download_type'] == 'full':
                    # 整本下载
                    book_name = book.get_formatted_title(config.get('download', 'full_title'))
                    file_path = os.path.join(NOVEL_PATH, book_name, f"{book_name}.epub")
                elif task_data['download_type'] == 'volume' and task_data.get('volume_name'):
                    # 单卷下载
                    book_name = book.get_formatted_title(config.get('download', 'full_title'))
                    volume_name = task_data['volume_name']
                    file_path = os.path.join(NOVEL_PATH, book_name, f"{volume_name}.epub")
                
                if file_path and os.path.exists(file_path):
                    self._add_book_to_library(book, file_path, task_data['download_type'])
                    
        except Exception as e:
            print(f"下载任务回调处理错误: {e}")